package com.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.six.mapper.DeptMapper;
import com.six.pojo.Dept;
import com.six.pojo.dto.DeptDto;
import com.six.pojo.vo.DeptVo;
import com.six.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
    @Autowired
    private DeptService deptService;

    @Override
    public Page<DeptDto> findAllByPageAndCondition(Page<Dept> page, DeptVo deptVo) {
        return baseMapper.findAllByPageAndCondition(page,deptVo);
    }

    @Override
    public List<Dept> selectDeptTree() {
        List<Dept> depts = deptService.list();
        List<Dept> deptList = new ArrayList<>();
        depts.forEach(dept->{
            if (dept.getParentId() == 0 || dept.getParentId()==null) {
                dept.setLevel(0);
                deptList.add(dept);
            }
        });
        findChildren(deptList,depts);
        return deptList;
    }
    private void findChildren(List<Dept> deptList,List<Dept> depts) {
        // 遍历所有的一级目录
        for (Dept dept:deptList) {
            // 构建子部门
            List<Dept> children = new ArrayList<>();
            for (Dept d:depts) {
                if (dept.getId() != null && dept.getId().equals(d.getParentId())) {
                    d.setParentName(dept.getDeptName());
                    d.setLevel(dept.getLevel()+1);
                    children.add(d);
                }
            }
            dept.setChildren(children);
            findChildren(children,depts);
        }
    }
}
